import { operationStatus } from '@/api'
export const addZXJ = async () => {
  await __g.marker.clear()
  await __g.customObject.clear()
  await __g.polyline.clear()
  let lines = []
  peopleList.forEach(async (item, index) => {
    lines.push({
      id: item.id, //折线唯一标识id
      coordinates: item.coor, //构成折线的坐标点数组
      coordinateType: 0, //坐标系类型，取值范围：0为Projection类型，1为WGS84类型，2为火星坐标系(GCJ02)，3为百度坐标系(BD09)，默认值：0
      range: [1, 10000000], //可视范围：[近裁距离, 远裁距离]，取值范围: [任意负值, 任意正值]
      thickness: 500, //折线宽度
      intensity: 5,
      color: '#f8fb00',
      shape: 1, //折线类型 0：直线， 1：曲线  注意：设置为曲线非常影响添加效率
      depthTest: false, //是否做深度检测 开启后会被地形高度遮挡
      style: 1, //折线样式 参考样式枚举：PolylineStyle
      tiling: 0, //材质贴图平铺比例
      userData: JSON.stringify(item)
    })
  })
  __g.polyline.add(lines)
  // 添加飞行器
  addCusObjectDa(peopleList)
  // 飞行器行走
  cusObjectDaMove(peopleList)
  //更新文字标签
  updateMarkerText()

  //添加机舱
  addJc()
}

export const peopleList = [
  {
    id: '政务巡检',
    coor: [
      [523925.363708679, 2495767.0872210353, 300],
      [523847.4490151413, 2495531.477799286, 300],
      [523753.9769072696, 2495199.426795317, 300],
      [523848.33359473455, 2494922.4781049974, 300],
      [523780.7237807818, 2494605.248754132, 300],
      [524267.2598122969, 2495106.797515634, 300],
      [524248.8424402716, 2495463.0837522037, 300],
      [524299.1635487783, 2495804.293112741, 300],
      [524564.0483911687, 2496098.4548640735, 300],
      [525068.7251104941, 2496762.180486174, 300],
      [524556.6861642079, 2496329.4688396784, 300],
      [524159.011818528, 2496014.3883736334, 300],
      [523992.0981813116, 2495822.2085724063, 300]
    ],
    jd: 0,
    name: '政务巡检',
    imagePath: window.origin + `/poi/poi_人员@2x.png`,
    popupURL:
      window.origin +
      '/popup/zhishenji.html?parmas=' +
      encodeURIComponent(
        JSON.stringify({
          id: '政务巡检',
          name: '巡检无人机'
        })
      ),
    assetPath: '/JC_CustomAssets/ObjectLibrary/Exhibition/盐田低空无人机/无人机1',
    groupId1: 'zwxjCusObjectDaGroup',
    groupId2: 'zwxCusObjectDaMarker'
  },
  {
    id: '政务巡检1',
    coor: [
      [525596.0108024944, 2499373.3248024895, 300],
      [525375.285863358, 2499533.842397272, 300],
      [524889.6496719915, 2499910.9712094786, 300],
      [524585.0185409861, 2500256.3365926947, 300],
      [524488.5221796872, 2500070.3082654243, 300],
      [524619.8931074423, 2499814.473694949, 300],
      [524804.8652510376, 2499259.2268111007, 300],
      [525417.8119248351, 2498980.6921680365, 300],
      [525861.806893699, 2498781.5154696344, 300],
      [526451.7767574314, 2498664.628291876, 300],
      [526788.641513855, 2498968.24352486, 300],
      [527140.0925180205, 2499053.4840284064, 300],
      [527469.2180756495, 2499029.145784817, 300],
      [526760.1687502785, 2499123.64100973, 300],
      [526174.7923769227, 2499312.5954844505, 300],
      [525912.8461641219, 2499339.5874552154, 300]
    ],
    jd: 0,
    name: '政务巡检1',
    imagePath: window.origin + `/poi/poi_人员@2x.png`,
    popupURL:
      window.origin +
      '/popup/zhishenji.html?parmas=' +
      encodeURIComponent(
        JSON.stringify({
          id: '政务巡检1',
          name: '巡检无人机1'
        })
      ),
    assetPath: '/JC_CustomAssets/ObjectLibrary/Exhibition/盐田低空无人机/无人机1',
    groupId1: 'zwxjCusObjectDaGroup',
    groupId2: 'zwxCusObjectDaMarker'
  }
]

/**
 * 点击出现弹框
 * @param e
 */
export const showDialogzwxj = async (e) => {
  if (e.GroupID === 'zwxCusObjectDaMarker') {
    clearInterval(window.timer)
    __g.polyline.setThickness(e.Id, -1)
    __g.customObject.focus(e.Id, -1)
    return
  }
}

/**
 * 添加飞行器
 */
export const addCusObjectDa = async (List) => {
  let pList = []
  let pList1 = []
  List.forEach(async (item, index) => {
    item.coor.forEach(async (it, i) => {
      if (i === 0) {
        let o = {
          id: item.id, //自定义对象唯一id
          pakFilePath: '@path:DTS_Library.pak',
          assetPath: item.assetPath,
          location: it, //位置坐标
          coordinateType: 0, // 坐标系类型
          rotation: [0, 0, 0], // 世界坐标系旋转
          range: [0, 10000000], //可见范围
          groupId: item.groupId1, //分组id
          localRotation: [0, item.jd, 0], //模型自身旋转
          scale: [1, 1, 1], //模型缩放
          isEffectRotation: true, //是否开启旋转效果
          smoothMotion: 1, //1: 平滑移动，0: 跳跃移动
          supportAttach: false, //不支持贴画贴合
          visible: true, //模型加载后默认是否显示
          autoHeight: false //是否开启自动高度 开启后自动贴地不再使用坐标Z
        }
        pList.push(o)
        let o1 = {
          id: item.id, //maker唯一标识
          groupId: item.groupId2,
          coordinate: it, //坐标位置
          coordinateType: 0, //坐标系类型
          imagePath: item.imagePath, //图片路径
          anchors: [-25, 50],
          imageSize: [50, 50],
          fixedSize: true,
          text: '',
          fontColor: '#ffffff',
          fontSize: 12,
          textRange: [1, 2000000000],
          textBackgroundColor: '#008214',
          range: [1, 2000000000], //标签的可见范围 [Min,Max]
          autoHidePopupWindow: true,
          autoHeight: false,
          occlusionCull: false,
          popupURL: item.popupURL, //弹窗HTML链接
          // popupBackgroundColor: [1.0, 1.0, 1.0, 0.5],//弹窗背景颜色
          popupSize: [250, 180], //弹窗大小
          popupOffset: [-130, -100], //弹窗偏移
          showLine: false, //标注点下方是否显示垂直牵引线
          displayMode: 4, //智能显示模式  开发过程中请根据业务需求判断使用四种显示模式
          clusterByImage: true, // 聚合时是否根据图片路径分类，即当多个marker的imagePath路径参数相同时按路径对marker分类聚合
          priority: 0 //避让优先级
        }
        pList1.push(o1)
      }
    })
  })
  __g.customObject.add(pList)
  __g.marker.add(pList1)

  pList.forEach(async (item) => {
    __g.customObject.callBPFunction([
      {
        id: item.id,
        functionName: '状态',
        parameters: [
          { paramType: 0, paramValue: 1 },
          { paramType: 3, paramValue: 2 }
        ]
      }
    ])
    __g.marker.setAttachCustomObject([
      {
        markerId: item.id, //标注id
        objectId: item.id, //自定义对象id
        offset: [0, 0, 0] //偏移量
      }
    ])
  })
}

//更新标签内容
function random(m, n) {
  return Number(m + Math.random() * (n - m)).toFixed(1)
}
export const updateMarkerText = () => {
  if (window.timer) {
    clearInterval(window.timer)
  }
  window.timer = null
  window.timer = setInterval(() => {
    peopleList.forEach((item) => {
      __g.marker.update({
        id: item.id,
        text: `类型：无人机\n高度：${random(50, 70)}m\n速度：${random(6, 10)}m/s`
      })
    })
  }, 2000)
}

/**
 * 飞行器行走
 * @param List 列表
 * @param speedPeople 速度
 */
export const cusObjectDaMove = async (List, speedPeople = 40) => {
  List.forEach((item, index) => {
    //构造移动路径点数组
    let pathPointArr = []
    let sum = 0
    for (let i = 0; i < item.coor.length - 1; i++) {
      //构造数组元素 每1秒移动一次
      let elementPoint = { time: sum, coordinate: item.coor[i] }
      pathPointArr.push(elementPoint)
      sum += computedDistance(item.coor[i], item.coor[i + 1]) / speedPeople
    }
    // 最后一项
    let elementPoint = {
      time: sum + (sum / item.coor.length - 1),
      coordinate: item.coor[item.coor.length - 1]
    }
    pathPointArr.push(elementPoint)

    //车辆按GPS轨迹移动
    __g.customObject.startMove(List[index].id, 0, pathPointArr)
    // __g.customObject.focus(peopleList[0].id)
  })
}

//添加机舱点位
const jclist = [
  {
    name: '华大时空中心楼顶',
    lon: 114.310202,
    lat: 22.605884
  },
  {
    name: '大梅沙大草坪西侧临时起降点',
    lon: 114.301248,
    lat: 22.593783
  },
  {
    name: '恩上水库',
    lon: 114.229747,
    lat: 22.571348
  },
  {
    name: '山海四季城',
    lon: 114.24948,
    lat: 22.595039
  },
  {
    name: '壹海城机巢',
    lon: 114.233683,
    lat: 22.557185
  },
  {
    name: '中英街机巢',
    lon: 114.230637,
    lat: 22.547663
  }
]
export async function addJc() {
  const { data } = await operationStatus({ flyType: 4 })
  const list = data.hangarList
  const markerArr = []
  list.forEach((item, index) => {
    let o = {
      id: `jc` + index, //maker唯一标识
      groupId: 'jc',
      coordinate: [Number(item.lon), Number(item.lat)], //坐标位置
      coordinateType: 1, //坐标系类型
      imagePath: window.origin + '/poi/机舱.png',
      anchors: [-25, 50],
      imageSize: [50, 50],
      fixedSize: true,
      range: [0, 20000000], //标签的可见范围 [Min,Max]
      autoHidePopupWindow: true,
      userData: JSON.stringify(item),
      displayMode: 2, //显示模式
      // priority: 0, //避让优先级
      autoHeight: true,
      occlusionCull: false
    }
    markerArr.push(o)
  })
  await __g.marker.add(markerArr)
}

/**
 * 计算投影坐标中空间两点的距离
 */
const computedDistance = (coord1, coord2) => {
  const [x1, y1, z1] = coord1
  const [x2, y2, z2] = coord2

  const deltaX = x2 - x1
  const deltaY = y2 - y1
  const deltaZ = z2 - z1

  const distance = Math.sqrt(deltaX ** 2 + deltaY ** 2 + deltaZ ** 2)
  return distance
}
